import 'package:flutter/material.dart';

/// @author jltxseo
///         Created by junlintianxia on 2020/04/22.

class CounterRoute extends StatelessWidget {
  const CounterRoute({super.key});

  @override
  Widget build(BuildContext context) {
    return CounterWidget();
  }
}

class CounterWidget extends StatefulWidget {
  final int initValue;

  const CounterWidget({super.key, this.initValue = 0});

  @override
  CounterWidgetState createState() => CounterWidgetState();
}

class CounterWidgetState extends State<CounterWidget>
    with WidgetsBindingObserver {
  int _counter = 0;

  /// Widget第一次插入到Widget树时会被调用
  @override
  Future<void> initState() async {
    super.initState();
    //初始化状态
    _counter = widget.initValue;
    WidgetsBinding.instance.addObserver(this);
    print("initState");
  }

  @override
  Widget build(BuildContext context) {
    print("build");
    return Scaffold(
      body: Center(
        child: TextButton(
          child: Text('$_counter'),
          //点击后计数器自增
          onPressed: () => setState(
            () => ++_counter,
          ),
        ),
      ),
    );
  }

  ///热重载调用
  @override
  void didUpdateWidget(CounterWidget oldWidget) {
    print("didUpdateWidget");
    super.didUpdateWidget(oldWidget);
  }

  @override
  void deactivate() {
    print("deactive");
    super.deactivate();
  }

  ///热重载调用
  @override
  void reassemble() {
    print("reassemble");
    super.reassemble();
  }

  @override
  void didChangeDependencies() {
    print("didChangeDependencies");
    super.didChangeDependencies();
  }

  @override
  void didChangeMetrics() {
    print("didChangeMetrics");
    super.didChangeMetrics();
  }

  ///监听原生App在系统里面的生命周期
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.resumed:
        print("didChangeAppLifecycleState resumed");
        break;
      case AppLifecycleState.paused:
        print("didChangeAppLifecycleState paused");
        break;
      case AppLifecycleState.inactive:
        print("didChangeAppLifecycleState inactive");
        break;
      case AppLifecycleState.detached:
        print("didChangeAppLifecycleState detached");
        break;
      default:
        break;
    }
    super.didChangeAppLifecycleState(state);
  }

  @override
  void dispose() {
    print("dispose");
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }
}
